﻿using Microsoft.Extensions.Primitives;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace CallbackOfChangeTokenModeSample
{
    class Program
    {
        static CancellationTokenSource _cts;

        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Test();
            Console.ReadKey();
        }
        static void Test()
        {
            _ = Task.Factory.StartNew(() =>
            {
                do
                {
                    // 这里每隔十秒变化一次
                    Task.Delay(10000).Wait();
                    Console.WriteLine("发生变化了");
                    _cts.Cancel();
                } while (true);
            });

            ChangeToken.OnChange(
                () =>
                {
                    Console.WriteLine("监控进来了");
                    _cts = new CancellationTokenSource();
                    return new CancellationChangeToken(_cts.Token);
                }, () =>
                {
                    Console.WriteLine($"{DateTime.Now} 开始执行业务");
                    // 模拟耗时执行
                    Task.Delay(1000).Wait();
                    Console.WriteLine($"{DateTime.Now} 结束执行业务");
                    Console.WriteLine();
                });
        }
    }
}
